package com.neuedu.web.controller.yunong;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.neuedu.yunong.domain.YunongFamilyMemberInfo;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.neuedu.common.annotation.Log;
import com.neuedu.common.core.controller.BaseController;
import com.neuedu.common.core.domain.AjaxResult;
import com.neuedu.common.enums.BusinessType;
import com.neuedu.yunong.domain.YunongHouseholdInfo;
import com.neuedu.yunong.service.IYunongHouseholdInfoService;
import com.neuedu.common.utils.poi.ExcelUtil;
import com.neuedu.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 户主信息Controller
 *
 * @author zl
 * @date 2024-12-10
 */
@RestController
@RequestMapping("/household/info")
@Tag(name = "【户主信息】管理")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class YunongHouseholdInfoController extends BaseController {
    private final IYunongHouseholdInfoService yunongHouseholdInfoService;

    /**
     * 查询户主信息列表
     */
    @Operation(summary = "查询户主信息列表")
    @PreAuthorize("@ss.hasPermi('household:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(YunongHouseholdInfo yunongHouseholdInfo) {
        startPage();
        List<YunongHouseholdInfo> list = yunongHouseholdInfoService.selectYunongHouseholdInfoList(yunongHouseholdInfo);
        return getDataTable(list);
    }

    /**
     * 导出户主信息列表
     */
    @Operation(summary = "导出户主信息列表")
    @PreAuthorize("@ss.hasPermi('household:info:export')")
    @Log(title = "户主信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YunongHouseholdInfo yunongHouseholdInfo) {
        List<YunongHouseholdInfo> list = yunongHouseholdInfoService.selectYunongHouseholdInfoList(yunongHouseholdInfo);
        ExcelUtil<YunongHouseholdInfo> util = new ExcelUtil<YunongHouseholdInfo>(YunongHouseholdInfo.class);
        util.exportExcel(response, list, "户主信息数据");
    }

    /**
     * 获取户主信息详细信息
     */
    @Operation(summary = "获取户主信息详细信息")
    @PreAuthorize("@ss.hasPermi('household:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(yunongHouseholdInfoService.selectYunongHouseholdInfoById(id));
    }

    /**
     * 新增户主信息
     */
    @Operation(summary = "新增户主信息")
    @PreAuthorize("@ss.hasPermi('household:info:add')")
    @Log(title = "户主信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YunongHouseholdInfo yunongHouseholdInfo) {
        return toAjax(yunongHouseholdInfoService.insertYunongHouseholdInfo(yunongHouseholdInfo));
    }

    /**
     * 修改户主信息
     */
    @Operation(summary = "修改户主信息")
    @PreAuthorize("@ss.hasPermi('household:info:edit')")
    @Log(title = "户主信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YunongHouseholdInfo yunongHouseholdInfo) {
        return toAjax(yunongHouseholdInfoService.updateYunongHouseholdInfo(yunongHouseholdInfo));
    }

    /**
     * 删除户主信息
     */
    @Operation(summary = "删除户主信息")
    @PreAuthorize("@ss.hasPermi('household:info:remove')")
    @Log(title = "户主信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable(name = "ids") Long[] ids) {
        return toAjax(yunongHouseholdInfoService.deleteYunongHouseholdInfoByIds(ids));
    }

    /**
     * 新增户主及家庭成员信息
     */
    @Operation(summary = "新增户主及家庭成员信息")
    @PreAuthorize("@ss.hasPermi('household:info:add')")
    @Log(title = "户主信息", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public AjaxResult addHouseholdWithMembers(@RequestBody Map<String, Object> data) {
        // 提取数据
        Map<String, Object> householdMap = (Map<String, Object>) data.get("household");
        List<Map<String, Object>> familyMemberMaps = (List<Map<String, Object>>) data.get("familyMembers");

        // 转换为实体类
        YunongHouseholdInfo householdInfo = mapToHouseholdInfo(householdMap);
        List<YunongFamilyMemberInfo> familyMembers = mapToFamilyMemberInfoList(familyMemberMaps);

        // 调用服务层保存数据
        boolean success = yunongHouseholdInfoService.saveHouseholdWithMembers(householdInfo, familyMembers) > 0;

        // 返回统一的结果
        return success ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }


    private YunongHouseholdInfo mapToHouseholdInfo(Map<String, Object> data) {
        YunongHouseholdInfo info = new YunongHouseholdInfo();
        info.setName((String) Optional.ofNullable(data.get("name")).orElse(""));
        info.setGender((String) Optional.ofNullable(data.get("gender")).orElse(""));
        info.setBirthdate(data.containsKey("birthdate") ? convertToDate(parseToLocalDate((String) data.get("birthdate"))) : null);
        info.setIdCard((String) Optional.ofNullable(data.get("id_card")).orElse(""));
        info.setOccupation((String) Optional.ofNullable(data.get("occupation")).orElse(""));
        info.setEducation((String) Optional.ofNullable(data.get("education")).orElse(""));
        info.setContact((String) Optional.ofNullable(data.get("contact")).orElse(""));
        info.setWorkPlace((String) Optional.ofNullable(data.get("workplace")).orElse(""));
        info.setCurrentAddress((String) Optional.ofNullable(data.get("address")).orElse(""));
        info.setHouseholdNumber((String) Optional.ofNullable(data.get("household_number")).orElse(""));
        return info;
    }

    private List<YunongFamilyMemberInfo> mapToFamilyMemberInfoList(List<Map<String, Object>> dataList) {
        return dataList.stream()
                .map(data -> {
                    YunongFamilyMemberInfo member = new YunongFamilyMemberInfo();
                    member.setName((String) Optional.ofNullable(data.get("name")).orElse(""));
                    member.setGender((String) Optional.ofNullable(data.get("gender")).orElse(""));
                    member.setBirthdate(data.containsKey("birthdate") ? convertToDate(parseToLocalDate((String) data.get("birthdate"))) : null);
                    member.setIdCard((String) Optional.ofNullable(data.get("id_card")).orElse(""));
                    member.setRelationship((String) Optional.ofNullable(data.get("relationship")).orElse(""));
                    member.setOccupation((String) Optional.ofNullable(data.get("occupation")).orElse(""));
                    member.setEducation((String) Optional.ofNullable(data.get("education")).orElse(""));
                    member.setHealthStatus((String) Optional.ofNullable(data.get("health_status")).orElse(""));
                    member.setContact((String) Optional.ofNullable(data.get("contact")).orElse(""));
                    member.setCurrentAddress((String) Optional.ofNullable(data.get("current_address")).orElse(""));
                    return member;
                })
                .collect(Collectors.toList());
    }

    public static LocalDate parseToLocalDate(String isoDate) {
        return ZonedDateTime.parse(isoDate).toLocalDate();
    }

    // 工具方法：将 LocalDate 转换为 java.util.Date
    private Date convertToDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }


}
